package leetcode_141_160;

import utils.ListNode;

import java.util.HashSet;

public class hasCycle_141 {
    /**
     * 判断链表中是否有环。
     */
    public boolean hasCycle(ListNode head) {
        /**
         * 最简单的思路，建立hash表遍历所有元素
         * 11ms
         */
        HashSet<ListNode>set=new HashSet<>();
        while(head!=null){
            if(!set.add(head))
                return true;
            head=head.next;
        }
        return false;
    }


    public boolean hasCycle2(ListNode head) {
        /**
         * 按高解快慢指针思路尝试
         * 1ms
         */
        if (head == null || head.next == null) {
            return false;
        }
        ListNode root1=head;
        ListNode root2=head.next;
        while(root1!=null && root2!=null){
            if(root1.equals(root2))
                return true;
            root1=root1.next;
            if(root2.next==null)
                return false;
            root2=root2.next.next;
        }
        return false;
    }


    public boolean hasCycle3(ListNode head) {
        /**
         * 官解快慢指针
         * 0ms
         */
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {     //快慢指针相遇说明有环
            if (fast == null || fast.next == null) {  //链路有终点无环
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }

}
